<template>
  <div class="number-manage-container">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="号码搜索">
          <el-input
              v-model="searchForm.nums"
              placeholder="请输入完整号码"
              clearable
              @keyup.enter.native="handleSearch"
              @input="validateNumberInput"
          />
        </el-form-item>
        <el-form-item label="号码类型">
          <el-select
              v-model="searchForm.type"
              clearable
              placeholder="全部省份"
              @change="handleTypeChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(type, index) in this.navigationSearch.type"
                :key="index"
                :label="`${type.value}(${type.count})`"
                :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属省">
          <el-select
              v-model="searchForm.province"
              clearable
              placeholder="全部省份"
              @change="handleProvinceChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(province, index) in this.navigationSearch.province"
                :key="index"
                :label="`${province.value}(${province.count})`"
                :value="province.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属市">
          <el-select
              v-model="searchForm.city"
              clearable
              placeholder="全部市区"
              @change="handleCityChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(city, index) in this.navigationSearch.city"
                :key="index"
                :label="`${city.value}(${city.count})`"
                :value="city.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="报备资质">
          <el-select
              v-model="searchForm.qualification"
              clearable
              placeholder="全部"
              @change="handleQualificationChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(qualification, index) in this.navigationSearch.qualification"
                :key="index"
                :label="`${qualification.value}(${qualification.count})`"
                :value="qualification.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务场景">
          <el-input
              v-model="searchForm.businessScenario"
              placeholder="业务场景"
              clearable
          />
        </el-form-item>

        <el-form-item label="上游客户">
          <el-select
              v-model="searchForm.upstream"
              clearable
              placeholder="上游"
              @change="handleUpstreamChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(upstream, index) in this.navigationSearch.upstream"
                :key="index"
                :label="`${upstream.value}(${upstream.count})`"
                :value="upstream.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="成本月租">
          <el-input
              v-model="searchForm.monthlyRent"
              placeholder="格式xxx.0"
              clearable
          />
        </el-form-item>
        <el-form-item label="单号并发">
          <el-input
              v-model="searchForm.concurrent"
              placeholder="单号并发"
              clearable
          />
        </el-form-item>
        <el-form-item label="管控频次">
          <el-input
              v-model="searchForm.controlFrequency"
              placeholder="单号并发"
              clearable
          />
        </el-form-item>

        <el-form-item label="客户">
          <el-select
              v-model="searchForm.client"
              clearable
              placeholder="客户"
              @change="handleClientChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(client, index) in this.navigationSearch.client"
                :key="index"
                :label="`${client.value}(${client.count})`"
                :value="client.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目">
          <el-input
              v-model="searchForm.project"
              placeholder="项目"
              clearable
          />
        </el-form-item>
        <el-form-item label="销售月租">
          <el-input
              v-model="searchForm.salesMonthlyRent"
              placeholder="销售月租"
              clearable
          />
        </el-form-item>
        <el-form-item label="销售月租">
          <el-input
              v-model="searchForm.remark"
              placeholder="备注"
              clearable
          />
        </el-form-item>
        <el-form-item label="独享状态">
          <el-select
              v-model="searchForm.exclusiveStatus"
              clearable
              placeholder="全部"
          >
            <el-option label="全部" value="" />
            <el-option label="独享" value="独享" />
            <el-option label="号码池" value="号码池" />
          </el-select>
        </el-form-item>

        <el-form-item label="上架状态">
          <el-select
              v-model="searchForm.state"
              clearable
              placeholder="上架状态"
              @change="handleStateChange"
          >
            <!-- 全部选项 -->
            <el-option
                label="全部"
                :value="null"
            />
            <!-- 动态省份选项 -->
            <el-option
                v-for="(state, index) in this.navigationSearch.state"
                :key="index"
                :label="`${state.value}(${state.count})`"
                :value="state.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showImportDialog">导入号码</el-button>
      <el-button @click="handleExport">导出数据</el-button>
      <el-button
          type="primary"
          :disabled="selectedIds.length === 0"
          @click="handleExportSelected"
      >导出选中</el-button>
      <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
      >删除选中</el-button>

      <el-button
          type="warning"
          @click="showDeactivateDialog"
      >批量下架</el-button>
      <el-button @click="showBatchQueryDialog">通过文件批量查询</el-button>
      <el-button type="primary" :disabled="selectedIds.length === 0" @click="showBatchEditDialog">批量编辑</el-button>
      <el-button type="success" @click="showAddDialog">单条添加</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%;"
        stripe
    >
      <el-table-column type="selection" width="55" />
<!--      <el-table-column style="user-select: text" prop="num" label="手机号码" width="160" />-->
      <el-table-column prop="num" label="手机号码" width="160">
        <template slot-scope="{row}">
          <div style="user-select: text; cursor: text">
            {{ row.num }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="号码类型" width="160" />
      <el-table-column prop="province" label="归属地" width="120">
        <template slot-scope="{row}">
          <span>{{ row.province || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="city" label="城市" width="120">
        <template slot-scope="{row}">
          <span>{{ row.city || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="号码状态" width="160" />
      <el-table-column prop="client" label="客户" width="160" />
      <el-table-column prop="qualification" label="报备资质" width="260" />
      <el-table-column prop="business_scenario" label="业务场景" width="160" />
      <el-table-column prop="upstream" label="上游客户" width="160" />
      <el-table-column prop="monthly_rent" label="成本月租" width="160" />
      <el-table-column prop="concurrent" label="单号并发" width="160" />
      <el-table-column prop="control_frequency" label="管控频次" width="160" />
      <el-table-column prop="exclusive_status" label="是否独享" width="160" />
      <el-table-column prop="effective_date" label="上架时间" width="160" />
      <el-table-column prop="project" label="项目" width="160" />
      <el-table-column prop="sales_monthly_rent" label="销售月租" width="160" />
      <el-table-column prop="removal_time" label="下架时间" width="160" />
      <el-table-column prop="remark" label="备注" width="160" />
      <el-table-column label="操作" width="150" fixed="right">
        <template slot-scope="{row}">
          <el-button type="text" @click="showEditDialog(row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        :current-page="pagination.current"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100,500,1000]"
        :background="true"
        layout="total, sizes, prev, pager, next"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 导入弹窗 -->
    <el-dialog
        :visible.sync="importVisible"
        title="批量导入"
        width="40%"
    >
      <el-upload
          class="upload-wrapper"
          drag
          :action="uploadUrl"
          :headers="uploadHeaders"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          支持扩展名：.xlsx（<el-link type="primary" @click="downloadTemplate">下载模板</el-link>）
        </div>
      </el-upload>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
        :visible.sync="editVisible"
        :title="`编辑号码 - ${currentEdit.num}`"
        width="600px"
    >
      <el-form :model="currentEdit" label-width="100px">
        <!-- 已存在的字段 -->
        <el-form-item label="手机号码">
          <el-input v-model="currentEdit.num" disabled />
        </el-form-item>
        <el-form-item label="归属地">
          <el-input v-model="currentEdit.province" disabled/>
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="currentEdit.city" disabled/>
        </el-form-item>

        <!-- 新增字段 -->
        <el-form-item label="业务场景">
          <el-input v-model="currentEdit.business_scenario" placeholder="请输入业务场景"/>
        </el-form-item>

        <el-form-item label="上游来源">
          <el-input v-model="currentEdit.upstream" placeholder="请输入上游来源"/>
        </el-form-item>

        <el-form-item label="成本月租">
          <el-input
              v-model="currentEdit.monthly_rent"
              placeholder="请输入月租"/>
        </el-form-item>

        <el-form-item label="并发数量">
          <el-input v-model="currentEdit.concurrent" placeholder="请输入并发数"/>
        </el-form-item>
        <el-form-item label="管控频次">
          <el-input
              v-model="currentEdit.control_frequency"
              placeholder="请输入管控频次"/>
        </el-form-item>

        <el-form-item label="所属项目">
          <el-input v-model="currentEdit.project" placeholder="请输入项目名称"/>
        </el-form-item>

        <el-form-item label="销售月租">
          <el-input
              v-model="currentEdit.sales_monthly_rent"
              placeholder="请输入销售月租"/>
        </el-form-item>

        <!-- 原有选择器 -->
        <el-form-item label="状态">
          <el-select v-model="currentEdit.state" clearable>
            <el-option label="未上架" value="未上架"/>
            <el-option label="已上架" value="已上架"/>
            <el-option label="已下架" value="已下架"/>
          </el-select>
        </el-form-item>

        <el-form-item label="独享状态">
          <el-select v-model="currentEdit.exclusive_status" clearable>
            <el-option label="独享" value="独享"/>
            <el-option label="号码池" value="号码池"/>
          </el-select>
        </el-form-item>

        <!-- 多行文本 -->
        <el-form-item label="备注信息">
          <el-input
              v-model="currentEdit.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirmEdit">保存</el-button>
      </template>
    </el-dialog>
    <!-- 在弹窗部分添加批量下架弹窗 -->
    <el-dialog
        :visible.sync="deactivateVisible"
        title="批量下架"
        width="40%"
    >
      <el-upload
          class="upload-wrapper"
          drag
          :action="deactivateUrl"
          :headers="uploadHeaders"
          :before-upload="beforeDeactivateUpload"
          :on-success="handleDeactivateSuccess"
          :on-error="handleDeactivateError"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          支持扩展名：.xlsx 或 .txt（<el-link type="primary" @click="downloadDeactivateTemplate">下载模板</el-link>）
        </div>
      </el-upload>
    </el-dialog>
    <!-- 批量查询弹窗 -->
    <el-dialog
        :visible.sync="batchQueryVisible"
        title="批量查询"
        width="40%"
    >
      <el-upload
          class="upload-wrapper"
          drag
          :auto-upload="false"
          :on-change="handleBatchQueryFileChange"
          :show-file-list="false"
          accept=".xlsx,.txt"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          支持扩展名：.xlsx 或 .txt（每行/每单元格一个号码）
        </div>
      </el-upload>

      <div v-if="batchQueryData.length > 0" class="query-results">
        <el-table
            :data="batchQueryData"
            height="300"
            border
            stripe
        >
          <el-table-column prop="num" label="手机号" width="150" />
          <el-table-column prop="state" label="状态" width="100" />
          <el-table-column prop="province" label="归属地" />
          <el-table-column prop="exclusive-status" label="独享状态" />
          <el-table-column prop="client" label="所属客户" />
        </el-table>

        <el-pagination
            :current-page="batchQueryPage.current"
            :page-size="batchQueryPage.size"
            :total="batchQueryPage.total"
            layout="total, prev, pager, next"
            @current-change="handleBatchQueryPageChange"
        />
      </div>
    </el-dialog>
    <!-- 批量编辑弹窗 -->
    <el-dialog
        :visible.sync="batchEditVisible"
        title="批量编辑"
        width="600px"
    >
      <div class="batch-edit-wrapper">
        <!-- 已选ID展示 -->
        <div class="selected-ids">
          <el-tag
              v-for="id in selectedIds"
              :key="id"
              closable
              @close="removeSelectedId(id)"
          >{{ id }}</el-tag>
        </div>

        <!-- 编辑表单 -->
        <el-form ref="batchEditForm" :model="batchEditForm" label-width="100px">
          <el-form-item label="状态">
            <el-select
                v-model="batchEditForm.state"
                placeholder="请选择状态"
                clearable
            >
              <el-option label="未上架" value="未上架"/>
              <el-option label="已上架" value="已上架"/>
              <el-option label="已下架" value="已下架"/>
              <el-option label="已退订" value="已退订"/>
            </el-select>
          </el-form-item>

          <el-form-item label="独享状态">
            <el-select
                v-model="batchEditForm.exclusiveStatus"
                placeholder="请选择独享状态"
                clearable
            >
              <el-option label="独享" value="独享"/>
              <el-option label="号码池" value="号码池"/>
            </el-select>
          </el-form-item>

          <el-form-item label="号码类型">
            <el-select
                v-model="batchEditForm.type"
                placeholder="请选择号码类型"
                clearable
            >
              <el-option label="手机号码" value="手机号码"/>
              <el-option label="固话" value="固话"/>
            </el-select>
          </el-form-item>

          <el-form-item label="业务场景">
            <el-input
                v-model="batchEditForm.businessScenario"
                placeholder="输入业务场景"
            />
          </el-form-item>
          <el-form-item label="客户">
            <el-input
                v-model="batchEditForm.client"
                :rows="3"
                placeholder="输入客户信息"
            />
          </el-form-item>
          <el-form-item label="上游信息">
            <el-input
                v-model="batchEditForm.upstream"
                :rows="3"
                placeholder="输入上游信息"
            />
          </el-form-item>
          <el-form-item label="备注信息">
            <el-input
                v-model="batchEditForm.remark"
                type="textarea"
                :rows="3"
                placeholder="输入备注信息"
            />
          </el-form-item>
        </el-form>
      </div>

      <template slot="footer">
        <el-button @click="batchEditVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchEdit">保存修改</el-button>
      </template>
    </el-dialog>
    <!-- 添加弹窗 -->
    <el-dialog
        :visible.sync="addVisible"
        title="新增号码"
        width="700px"
    >
      <el-form
          ref="addForm"
          :model="addForm"
          label-width="120px"
          :rules="addRules"
      >
        <!-- 基础信息 -->
        <el-form-item label="手机号码" prop="num">
          <el-input
              v-model="addForm.num"
              placeholder="11位数字"
              maxlength="11"
              clearable
          />
        </el-form-item>

        <el-form-item label="归属地" prop="province">
          <el-input v-model="addForm.province" placeholder="例：辽宁"/>
        </el-form-item>

        <el-form-item label="城市" prop="city">
          <el-input v-model="addForm.city" placeholder="例：沈阳市"/>
        </el-form-item>
        <el-form-item label="号码类型" prop="type">
          <el-input v-model="addForm.type" placeholder="例：手机号码"/>
        </el-form-item>

        <!-- 业务信息 -->
        <el-form-item label="业务场景">
          <el-input
              v-model="addForm.business_scenario"
              placeholder="请输入业务场景"
          />
        </el-form-item>

        <el-form-item label="上游来源">
          <el-input v-model="addForm.upstream" placeholder="上游客户名称"/>
        </el-form-item>

        <!-- 财务信息 -->
        <el-form-item label="成本月租" prop="monthly_rent">
          <el-input
              v-model="addForm.monthly_rent"
              placeholder="0.00"
              type="number"
              step="0.01"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="销售月租">
          <el-input
              v-model="addForm.sales_monthly_rent"
              placeholder="0.00"
              type="number"
              step="0.01"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <!-- 管控信息 -->
        <el-form-item label="并发数量">
          <el-input
              v-model="addForm.concurrent"
              type="number"
              placeholder="整数"
          />
        </el-form-item>

        <el-form-item label="管控频次">
          <el-input
              v-model="addForm.control_frequency"
              placeholder="例：每日3次"
          />
        </el-form-item>

        <!-- 状态信息 -->
        <el-form-item label="状态" prop="state">
          <el-select
              v-model="addForm.state"
              placeholder="请选择"
              clearable
          >
            <el-option label="未上架" value="未上架"/>
            <el-option label="已上架" value="已上架"/>
            <el-option label="已下架" value="已下架"/>
          </el-select>
        </el-form-item>

        <el-form-item label="独享状态">
          <el-select
              v-model="addForm.exclusive_status"
              placeholder="请选择"
              clearable
          >
            <el-option label="独享" value="独享"/>
            <el-option label="号码池" value="号码池"/>
          </el-select>
        </el-form-item>

        <!-- 扩展信息 -->
        <el-form-item label="所属项目">
          <el-input v-model="addForm.project" placeholder="项目名称"/>
        </el-form-item>

        <el-form-item label="客户信息">
          <el-input v-model="addForm.client" placeholder="客户名称"/>
        </el-form-item>

        <el-form-item label="报备资质">
          <el-input
              v-model="addForm.qualification"
              type="textarea"
              :rows="2"
              placeholder="资质说明"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
              v-model="addForm.remark"
              type="textarea"
              :rows="3"
              placeholder="其他备注信息"
          />
        </el-form-item>
      </el-form>

      <template slot="footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmAdd"
            :loading="adding"
        >提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { saveAs } from 'file-saver'

export default {
  data() {
    return {
      searchForm: {
        nums:'',
        province: '',
        city: '',
        state: '',
        businessScenario:'',
        upstream:'',
        monthlyRent:'',
        concurrent:'',
        controlFrequency:'',
        exclusiveStatus:'',
        project:'',
        salesMonthlyRent:'',
        remark:''
      },
      nullForm:{},
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      tableData: [],
      loading: false,
      selectedIds: [],
      importVisible: false,
      editVisible: false,
      currentEdit: {
        id: null,
        number: '',
        province: '',
        city: '',
        package: '',
        status: 1,
        state:'',
        exclusive_status:'',
        business_scenario:'',
        monthly_rent:'',
        control_frequency:'',
        sales_monthly_rent:'',
        concurrent:''
      },
      batchQueryVisible: false,
      batchQueryFile: null,
      batchQueryPage: {
        current: 1,
        size: 10,
        total: 0
      },
      batchQueryData: [],
      deactivateVisible:false,
      batchEditVisible: false,
      batchEditForm: {
        state: '',
        exclusiveStatus: '',
        businessScenario: '',
        remark: '',
        client:'',
        upstream:'',
        removalTime:''
      },
      addVisible: false,
      adding: false,
      addForm: {
        num: '',
        province: '',
        city: '',
        type:'',
        business_scenario: '',
        upstream: '',
        monthly_rent: null,
        sales_monthly_rent: null,
        concurrent: null,
        control_frequency: '',
        state: '',
        exclusive_status: '',
        project: '',
        client: '',
        qualification: '',
        remark: ''
      },
      navigationSearch:{},
      targetFields:[],
      currentFilters: {},
      navigationDate:[
      ],
      addRules: {
        num: [
          { required: true, message: '必填项', trigger: 'blur' },
          { pattern: /^\d{5,20}$/, message: '必须为5到20位数字' }
        ],
        province: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        type:[
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        monthly_rent: [
          {
            validator: (rule, value, callback) => {
              if (value !== null && (value < 0 || isNaN(value))) {
                callback(new Error('请输入有效数字'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        state: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    uploadUrl() {
      return `http://glxt.bjrhtd.com:9999/api/excel/import`
    },
    uploadHeaders() {
      return {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
        'X-Requested-With': 'XMLHttpRequest'
      }
    },
    deactivateUrl() {
      return `http://glxt.bjrhtd.com:9999/api/numbers/batchdeactivate`
    }
  },
  mounted() {
    this.fetchData()
    this.navigation()
  },

  methods: {
    //联动筛选
    navigation(){
      request.post("/api/navigation/smart-filter",
          {
            targetFields:this.targetFields,
            currentFilters:this.currentFilters
          }).then(res=>{
            this.navigationSearch = res.data
            console.log("navigationSearch",this.navigationSearch)
      })
    },
    // 数据获取
    async fetchData() {
      try {
        this.loading = true
        const params = {
          pageNum: this.pagination.current,
          pageSize: this.pagination.size,
          ...this.searchForm
        }
        console.log("qq")
        const res = await request.get('/api/numbers', { params })
        console.log(res)
        this.tableData = res.data
        this.pagination.total = res.total_elements
      } catch (error) {
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },

    // 分页处理
    handleSizeChange(newSize) {
      this.pagination.size = newSize
      this.fetchData()
    },
    handleCurrentChange(newPage) {
      this.pagination.current = newPage
      this.fetchData()
    },

    // 搜索处理
    handleSearch() {
      if (!this.validateNumbers()) return
      this.pagination.current = 1
      this.fetchData()
    },
    //重置条件
    reset(){
      this.searchForm={}
      this.targetFields=[]
      this.currentFilters= {}
      this.fetchData()
      this.navigation()
    },
    // 多选处理
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },

    // 状态变更
    async handleSingleStatusChange(row) {
      try {
        await request.put(`/api/numbers/${row.id}/status`, { status: row.status })
        this.$message.success('状态更新成功')
      } catch (error) {
        this.$message.error('状态更新失败')
        row.status = row.status === 1 ? 0 : 1 // 回滚状态
      }
    },


    // 导入处理
    showImportDialog() {
      this.importVisible = true
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$message.error('仅支持.xlsx格式文件')
        return false
      }
      return true
    },
    // eslint-disable-next-line no-unused-vars
    handleUploadSuccess(response, file, fileList) {
      console.log(response)
      // 统一处理不同版本参数结构
      const res = response?.response ? response.response : response;

      // 安全访问数据
      const importedRows = res.success;

      if (res?.code === 200) {
        this.$message.success(`导入完成，成功 ${importedRows} 条`);
        this.fetchData();
      } else {
        const errorMsg = res?.message || '导入失败，请检查文件格式';
        this.$message.error(errorMsg);
      }
      this.importVisible = false;
    },
    handleUploadError() {
      this.$message.error('文件上传失败，请检查网络连接')
    },

    // 导出处理
    async handleExport() {
      console.log("111")

      try {
        const res = await request.post('/api/excel/export',
            this.nullForm,
            {responseType: 'blob'}
        )
        saveAs(res, `号码数据_${new Date().toISOString()}.xlsx`)
        console.log("11",res)
      } catch (error) {
        this.$message.error('导出失败')
      }
    },
    //批量导出
    async handleExportSelected() {
      try {
        if (this.selectedIds.length === 0) return;

        // 确认操作
        await this.$confirm(`确认要导出选中的 ${this.selectedIds.length} 条数据吗？`, '导出确认', {
          type: 'warning'
        });

        // 调用导出接口
        const res = await request.post(
            '/api/excel/by-ids',
            { ids: this.selectedIds },
            { responseType: 'blob' } // 必须声明 responseType
        );

        // 解析文件名（优先从响应头获取）
        let filename = `选中号码_${this.selectedIds.length}条_${new Date().toLocaleDateString()}.xlsx`;
        const contentDisposition = res.headers['content-disposition'];
        if (contentDisposition) {
          const filenameRegex = /filename\*=UTF-8''(.+?\.xlsx)/i;
          const match = contentDisposition.match(filenameRegex);
          if (match?.[1]) {
            filename = decodeURIComponent(match[1]); // 解码 UTF-8 文件名
          }
        }

        // 创建 Blob 对象并验证
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        if (!blob || blob.size === 0) {
          throw new Error('导出的文件内容为空');
        }

        // 保存文件
        saveAs(blob, filename);
        this.$message.success('导出成功');

      } catch (error) {
        if (error === 'cancel') return; // 用户取消操作

        // 处理 Blob 类型的错误响应（如后端返回 JSON 错误）
        if (error.response?.data instanceof Blob) {
          const reader = new FileReader();
          reader.onload = () => {
            try {
              const errorData = JSON.parse(reader.result);
              this.$message.error(`导出失败: ${errorData.message || '未知错误'}`);
            } catch (e) {
              this.$message.error('导出失败: 无法解析错误信息');
            }
          };
          reader.readAsText(error.response.data);
        } else {
          this.$message.error(`导出失败: ${error.message || '未知错误'}`);
        }
      }
    },

    // 模板下载
    async downloadTemplate() {
      try {
        const res = await request.get('/api/excel/template',{responseType: 'blob'})
        saveAs(res, '号码模板.xlsx')
      } catch (error) {
        this.$message.error('模板下载失败')
      }
    },

    // 编辑处理
    showEditDialog(row) {
      Object.assign(this.currentEdit, row)
      console.log(row)
      this.editVisible = true
    },
    close(){
      this.currentEdit={}
      this.editVisible = false
    },
    async confirmEdit() {
      try {
        await request.put(`/api/numbers/${this.currentEdit.id}`, this.currentEdit)
        this.$message.success('修改成功')
        this.editVisible = false
        this.fetchData()
      } catch (error) {
        this.$message.error('修改失败')
      }
    },

    // 单个删除（已存在，补充确认逻辑）
    async handleDelete(id) {
      try {
        await this.$confirm('确认删除该号码吗？', '删除确认', {
          type: 'warning'
        });
        // 调用删除接口
        console.log(id)
        await request.delete(`/api/numbers/delete/${id}`);
        this.$message.success('删除成功');
        this.fetchData(); // 刷新数据
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + (error.message || '未知错误'));
        }
      }
    },
    // 批量删除选中
    async handleBatchDelete() {
      if (this.selectedIds.length === 0) return;

      try {
        await this.$confirm(`确认删除选中的 ${this.selectedIds.length} 条数据吗？`, '批量删除确认', {
          type: 'warning'
        });

        const res = await request.post('/api/numbers/delete/batch',
            {ids:this.selectedIds} );
        console.log(res)

        // 验证响应 code 和 data
        if (res.code == 200) {
          this.selectedIds = [];
          this.fetchData();
        } else {
          this.$message.error('删除失败: 未删除任何数据');
        }
      } catch (error) {
        if (error !== 'cancel') {
          // 显示具体错误信息
          const errorMsg = error.response?.data?.msg || error.message || '未知错误';
          this.$message.error(`批量删除失败: ${errorMsg}`);
        }
      }
    },
    //批量下架
    showDeactivateDialog() {
      this.deactivateVisible = true
    },

    // 文件上传前校验
    beforeDeactivateUpload(file) {
      const isAllowed = ['.xlsx', '.txt'].some(ext =>
          file.name.toLowerCase().endsWith(ext)
      )
      if (!isAllowed) {
        this.$message.error('仅支持 .xlsx 或 .txt 文件')
        return false
      }
      return true
    },
    handleDeactivateSuccess(res) {
      this.deactivateVisible = false
      if (res.code === 200) {
        let successMsg = `成功下架 ${res.data.processedCount} 条数据`
        if (res.data.failedIds?.length > 0) {
          successMsg += `，失败 ${res.data.failedIds.length} 条`
        }
        this.$message.success(successMsg)
        this.fetchData()
      } else {
        this.$message.error(res.message || '下架操作失败')
      }
    },
    // 处理下架错误
    handleDeactivateError(err) {
      const msg = err.response?.data?.message || '文件上传失败'
      this.$message.error(`下架失败: ${msg}`)
    },
    //文件查询
    // 显示批量查询弹窗
    showBatchQueryDialog() {
      this.batchQueryVisible = true
      this.batchQueryData = []
      this.batchQueryFile = null
    },

    // 文件选择变更
    handleBatchQueryFileChange(file) {
      const isAllowed = ['.xlsx', '.txt'].some(ext =>
          file.name.toLowerCase().endsWith(ext)
      )
      if (!isAllowed) {
        this.$message.error('仅支持 .xlsx 或 .txt 文件')
        return
      }
      this.batchQueryFile = file.raw
      this.submitBatchQuery()
    },

    // 提交查询请求
    async submitBatchQuery() {
      if (!this.batchQueryFile) return

      const formData = new FormData()
      formData.append('file', this.batchQueryFile)
      formData.append('currentPage', this.batchQueryPage.current)
      formData.append('pageSize', this.batchQueryPage.size)

      try {
        const res = await request.post('/api/numbers/bynum', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (res.code === 200) {
          this.batchQueryData = res.data
          this.batchQueryPage.total = res.totalElements
        } else {
          this.$message.error(res.message || '查询失败')
        }
      } catch (error) {
        this.$message.error('请求失败: ' + error.message)
      }
    },

    // 分页变更
    handleBatchQueryPageChange(newPage) {
      this.batchQueryPage.current = newPage
      this.submitBatchQuery()
    },
    // 显示批量编辑弹窗
    showBatchEditDialog() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要编辑的数据')
        return
      }
      this.batchEditVisible = true
      // 重置表单
      this.batchEditForm = {
        state: '',
        exclusiveStatus: '',
        businessScenario: '',
        remark: ''
      }
    },

    // 移除选中ID
    removeSelectedId(id) {
      this.selectedIds = this.selectedIds.filter(item => item !== id)
    },

    // 提交批量编辑
    async confirmBatchEdit() {
      try {
        // 构建请求参数
        const payload = {
          ids: this.selectedIds,
          updateData: this.batchEditForm
        }

        // 过滤空值字段
        Object.keys(payload).forEach(key => {
          if (payload[key] === '') delete payload[key]
        })

        const res = await request.post('/api/numbers/batch-full-update', payload)

        if (res.code === 200) {
          this.$message.success(`成功更新`)
          this.batchEditVisible = false
          this.fetchData() // 刷新表格数据
          this.selectedIds = [] // 清空选中项
        } else {
          this.$message.error(res.message || '更新失败')
        }
      } catch (error) {
        const errorMsg = error.response?.data?.message || error.message
        this.$message.error(`操作失败: ${errorMsg}`)
      }
    },
    validateNumberInput() {
      // 过滤非数字和逗号
      this.searchForm.nums = this.searchForm.nums.replace(/[^\d,]/g, '')
      // 自动去除重复逗号
      this.searchForm.nums = this.searchForm.nums.replace(/,+/g, ',')
    },
    validateNumbers() {
      if (!this.searchForm.nums) return true

      const numbers = this.searchForm.nums.split(',')
      const isValid = numbers.every(num => {
        return /^\d{5,20}$/.test(num)
      })

      if (!isValid) {
        this.$message.error('号码格式错误：必须为数字，多个号码用英文逗号分隔')
        return false
      }
      return true
    },
    // 显示添加弹窗
    showAddDialog() {
      this.addVisible = true
      this.$nextTick(() => {
        this.$refs.addForm?.resetFields()
      })
    },
    async confirmAdd() {
      try {
        // 表单验证
        await this.$refs.addForm.validate()

        // 发送请求
        const res = await request.post('/api/numbers', this.addForm)

        if (res.code === 200) {
          this.$message.success('新增成功')
          this.addVisible = false
          this.fetchData() // 刷新列表
        }
      } catch (error) {
        if (error.response?.data?.code === 4001) {
          this.$message.error('号码已存在')
        } else {
          this.$message.error('新增失败: ' + (error.message || '未知错误'))
        }
      }
    },
    handleProvinceChange(value){
      this.currentFilters.province = value
      this.searchForm.province = value
      this.navigation()
      console.log(value)
    },
    handleCityChange(value){
      this.currentFilters.city = value
      this.searchForm.city = value
      this.navigation()
      console.log(value)
    },
    handleQualificationChange(value){
      this.currentFilters.qualification = value
      this.searchForm.qualification = value
      this.navigation()
      console.log(value)
    },
    handleUpstreamChange(value){
      this.currentFilters.upstream = value
      this.searchForm.upstream = value
      this.navigation()
      console.log(value)
    },
    handleClientChange(value){
      this.currentFilters.client = value
      this.searchForm.client = value
      this.navigation()
      console.log(value)
    },
    handleStateChange(value){
      this.currentFilters.state = value
      this.searchForm.state = value
      this.navigation()
      console.log(value)
    },
    handleTypeChange(value){
      this.currentFilters.type = value
      this.searchForm.type = value
      this.navigation()
      console.log(value)
    },
    handleDateFocus(field) {
      if (!this.batchEditForm[field]) {
        this.batchEditForm[field] = this.$dayjs().format('YYYY-MM-DD HH:mm:ss');
      }
    },
    // 工具函数
    formatDate(timestamp) {
      return new Date(timestamp).toLocaleString()
    }
  }
}
</script>

<style scoped>
.number-manage-container {
  padding: 20px;
  background: #f5f7fa;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.upload-wrapper >>> .el-upload {
  width: 100%;
}

.el-upload__tip {
  margin-top: 10px;
  color: #606266;
}
.batch-edit-wrapper {
  .selected-ids {
    margin-bottom: 20px;
    max-height: 120px;
    overflow-y: auto;

    .el-tag {
      margin: 5px;
    }
  }

  .el-form-item {
    margin-bottom: 22px;

    .el-input, .el-select {
      width: 80%;
    }
  }
}
.add-form .el-input {
  width: 80%;
}
.add-form .el-select {
  width: 100%;
}
</style>